<template>
  <div class="upload-container">
    <el-upload
      class="image-uploader"
      :action="null"
      :http-request="customUpload"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :disabled="disabled"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    <div class="image-tip">{{ tip || '只能上传jpg/png格式图片，且不超过2MB' }}</div>
  </div>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { uploadProductImage } from '../../api/product'

const props = defineProps({
  value: {
    type: String,
    default: ''
  },
  modelValue: {
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  },
  tip: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

// 支持v-model和自定义事件两种方式
const internalValue = ref(props.modelValue || props.value || '')

// 计算图片完整URL
const imageUrl = computed(() => {
  if (!internalValue.value) return ''
  
  console.log('处理图片URL:', internalValue.value)
  // 如果已经是完整的URL，直接返回
  if (internalValue.value.startsWith('http')) return internalValue.value
  
  // 服务器基础URL
  const serverUrl = 'http://localhost:5000'
  
  // 确保路径包含uploads
  if (internalValue.value.startsWith('/uploads/')) {
    return `${serverUrl}${internalValue.value}`
  } else if (internalValue.value.startsWith('/')) {
    return `${serverUrl}/uploads${internalValue.value}`
  } else {
    return `${serverUrl}/uploads/${internalValue.value}`
  }
})

// 监听props变化
watch(() => props.modelValue, (newVal) => {
  console.log('外部modelValue变化:', newVal)
  internalValue.value = newVal
})

watch(() => props.value, (newVal) => {
  console.log('外部value变化:', newVal)
  internalValue.value = newVal
})

// 上传前验证
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isJpgOrPng) {
    ElMessage.error('上传图片只能是JPG或PNG格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过2MB!')
  }
  return isJpgOrPng && isLt2M
}

// 自定义上传实现
const customUpload = async (options) => {
  try {
    const { file } = options
    const formData = new FormData()
    formData.append('file', file)
    
    console.log('准备上传图片:', file.name)
    const res = await uploadProductImage(formData)
    console.log('上传响应:', res)
    
    if (res && res.url) {
      // 更新值并触发事件
      internalValue.value = res.url
      emit('update:modelValue', res.url)
      emit('change', res.url)
      
      ElMessage.success('上传成功')
    } else {
      console.error('上传响应缺少url字段:', res)
      ElMessage.error('上传失败: 响应格式不正确')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error(`上传失败: ${error.message || '未知错误'}`)
  }
}
</script>

<style scoped>
.upload-container {
  margin-bottom: 20px;
}

.image-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.image-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.image-tip {
  color: #999;
  font-size: 12px;
  margin-top: 5px;
  width: 178px;
}
</style> 